package com.jd.service.impl;

import com.common.model.Result;
import com.gavel.utils.StringUtils;
import com.jd.model.ShelvesTaskCondition;
import com.jd.model.VCShelvesTaskVO;
import com.jd.service.JDShelvesTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("jdShelvesTaskService")
public class JDShelvesTaskServiceImpl implements JDShelvesTaskService {

    private static Logger LOG = LoggerFactory.getLogger(JDShelvesTaskService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Result<VCShelvesTaskVO> loadTasks(ShelvesTaskCondition condition) {

        Result<VCShelvesTaskVO> result = new Result();

        List<Object> params = new ArrayList<>();

        StringBuilder whereCond = new StringBuilder(" where 1 =1 ");
        if (StringUtils.isNotBlank(condition.getState()) ) {
            whereCond.append("  and STATE = ? ");
            params.add(condition.getState());
        }

        if (StringUtils.isNotBlank(condition.getName()) ) {
            whereCond.append("  and NAME like ? ");
            params.add("%" + StringUtils.trim(condition.getName()) + "%");
        }

        try {
            String sql = "select * from VC_SHELVES_TASK ";

            String cnt_sql = "select count(1)  from VC_SHELVES_TASK ";

            int count = jdbcTemplate.queryForObject(cnt_sql + whereCond.toString(), params.toArray(new Object[params.size()]), Integer.class);


            int fromIndex = (condition.getPage() - 1)*condition.getLimit();
            int toIndex = condition.getPage()*condition.getLimit();

            if ( fromIndex > count ) {
                fromIndex = 0;
                toIndex = 0;
            } else if ( toIndex > count ) {
                toIndex = count;
            }

            params.add(fromIndex);
            params.add(toIndex);
            List<VCShelvesTaskVO> list = jdbcTemplate.query(sql + whereCond.toString() + " limit ?, ?", params.toArray(new Object[params.size()]), new BeanPropertyRowMapper(VCShelvesTaskVO.class));

            result.setCode(0);
            result.setCount(count);
            result.setData(list);

        } catch (Exception e) {
            LOG.error(e.getMessage());
        }

        return result;

    }

}
